package com.fs.controller;

import com.fs.controller.vo.Response;
import com.fs.global.CustomException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice(basePackages = "com.fs.controller")
public class ExceptionCollector implements ResponseBodyAdvice<Object> {

    //捕获自定义异常
    @ResponseStatus(HttpStatus.ACCEPTED)
    @ExceptionHandler(CustomException.class)
    public Map<String, Object> handleCustomException(CustomException ex) {
        return failResult(ex.getMessage());
    }

    //捕获参数校验异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map<String, Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        FieldError fieldError = e.getFieldError();
        if (fieldError != null) {
            return failResult(fieldError.getDefaultMessage());
        } else {
            return failResult(e.getMessage());
        }
    }

    //javax constraint校验异常
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException.class)
    public Map<String, Object> handleConstraintViolationException(ConstraintViolationException e) {
        return failResult(e.getMessage());
    }

    //request body转换失败(body为空)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Map<String, Object> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        return failResult("读取不到请求参数");
    }

    //捕获shiro授权异常
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(AuthorizationException.class)
    public Map<String, Object> handleUnknownAccountException(AuthorizationException e) {
        e.printStackTrace();
        return failResult("不具备访问权限");
    }

    //捕获shiro身份验证异常
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AuthenticationException.class)
    public Map<String, Object> handleAuthenticationException(AuthenticationException e) {
        e.printStackTrace();
        return failResult("鉴权失败");
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public Map<String, Object> handleException(Exception e) {
        e.printStackTrace();
        return failResult(e.getMessage());
    }

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.getContainingClass() != ExceptionHandler.class;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            return successResult();
        }
        if (body instanceof Response || body instanceof Map) {
            return body;
        }
        return new Response(body);
    }

    public static Map<String, Object> failResult(String errMsg) {
        Map<String, Object> map = new HashMap<>();
        map.put("success", false);
        map.put("message", errMsg);
        return map;
    }

    private Map<String, Object> successResult() {
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        map.put("message", "请求成功");
        return map;
    }
}
